package com.tg.app.activity.device.settings;

import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.widget.ListView;

import com.appbase.custom.base.SettingData;
import com.appbase.custom.constant.RecordModeConstants;
import com.demo.view.SettingItemTextView;
import com.tange.module.device.feature.DeviceFeatureObjectBox;
import com.tange.module.device.feature.DeviceFeature_;
import com.tg.app.R;
import com.tg.app.TGDevice;
import com.tg.app.activity.base.DeviceSettingsBaseActivity;
import com.tg.app.activity.device.DeviceSettingsActivity;
import com.tg.app.adapter.SettingAdapter;
import com.tange.module.device.feature.DeviceFeature;
import com.tg.app.camera.AVIOCTRLDEFs;
import com.tg.app.camera.Camera;
import com.tange.module.camera.hub.CameraHub;
import com.tg.app.helper.CameraBottomSheetDialogHelper;
import com.tg.app.helper.DeviceFeatureHelper;
import com.tg.app.widget.BottomSheetListDialog;
import com.demo.view.TGBottomSheetDialog;
import com.tg.appcommon.android.Packet;
import com.tg.appcommon.android.TGAlertDialog;
import com.tg.appcommon.android.TGLog;
import com.tange.base.toolkit.TGThreadPool;
import com.tg.appcommon.android.TGToast;
import com.tg.data.bean.DeviceSettingsInfo;
import com.tg.data.media.OnICameraListener;

import java.util.ArrayList;
import java.util.List;

import io.objectbox.Box;

public class SolarVideoSettingsActivity extends DeviceSettingsBaseActivity implements OnICameraListener {
    private DeviceSettingsInfo mDeviceSettingsInfo;
    private final ArrayList<SettingData> mTimesList = new ArrayList<>();
    private final ArrayList<SettingData> mLimpidList = new ArrayList<>();
    private SettingAdapter mTimesAdapter, mLimpidAdapter;
    private Camera mCamera;
    private DeviceFeature deviceFeature;
    protected BottomSheetListDialog bottomSheetListDialog;
    private int mSelectRecordType = RecordModeConstants.RECORD_MODE_AUTO;
    private int mLastSelectRecordType = 0;
    private byte mSelectRecordStream = 0;
    private byte mLastSelectRecordStream = 0;
    private int mSelectWakeMaxTime = 20;
    private int mLastSelectWakeMaxTime = 20;
    private SettingItemTextView settingItemTextView;
    @Override
    public void receiveUpdateConnectStates(int state) {
        TGLog.d(TGLog.TAG, "===mDeviceSettingsInfo.deviceStatus = " + state);
        if (state == Camera.CONNECTION_STATE_DISCONNECTED){
            TGThreadPool.executeOnUiThread(() -> {
                restoreRecordMode(mLastSelectRecordType);
                restoreRecordStream(mLastSelectRecordStream);
                restoreWakeMaxTime(mLastSelectWakeMaxTime);
            });
        }
    }

    @Override
    public boolean shouldSetStatusBarColor() {
        return true;
    }

    private void restoreWakeMaxTime(int lastSelectWakeMaxTime) {
        mSelectWakeMaxTime = lastSelectWakeMaxTime;
        TGLog.d(TGLog.TAG, "lastSelectWakeMaxTime" + lastSelectWakeMaxTime + ", mSelectWakeMaxTime = " + mSelectWakeMaxTime);
        if (mSelectWakeMaxTime == 20) {
            setFlag(mTimesList, 0);
        } else if (mSelectWakeMaxTime == 40) {
            setFlag(mTimesList, 1);
        } else if (mSelectWakeMaxTime == 60) {
            setFlag(mTimesList, 2);
        } else if (mSelectWakeMaxTime == 0) {
            setFlag(mTimesList, 3);
        }
        mTimesAdapter.notifyDataSetChanged();
    }

    private void restoreRecordStream(byte lastSelectRecordStream) {
        mSelectRecordStream = lastSelectRecordStream;
        TGLog.d(TGLog.TAG, "lastSelectRecordStream" + lastSelectRecordStream + ", mSelectRecordStream = " + mSelectRecordStream);
        setFlag(mLimpidList, mSelectRecordStream);
        mLimpidAdapter.notifyDataSetChanged();
    }

    private void restoreRecordMode(int lastSelectRecordType) {
        mSelectRecordType = lastSelectRecordType;
        setModeText(lastSelectRecordType);
        TGLog.d(TGLog.TAG, "lastSelectRecordType" + lastSelectRecordType + ", mSelectRecordType = " + mSelectRecordType);

    }

    @Override
    public void receiveIOCtrlData(int type, byte[] data) {
        if (type == AVIOCTRLDEFs.IOTYPE_USER_IPCAM_SETRECORD_RESP) {
            byte result = data[3];
            TGLog.d(TGLog.TAG, "type" + type + ", result = " + result);
            completeSend();
            if (result == 0) {
                runOnUiThread(() -> {
                    mDeviceSettingsInfo.recordType = mSelectRecordType;
                    mDeviceSettingsInfo.recordStream = mSelectRecordStream;
                    sendUpdateSettingBroadcast(mDeviceSettingsInfo);
                });
            }else{
                TGThreadPool.executeOnUiThread(() -> {
                    TGToast.showToast(R.string.setting_fail);
                    restoreRecordMode(mLastSelectRecordType);
                    restoreRecordStream(mLastSelectRecordStream);
                });

            }
        } else if (type == AVIOCTRLDEFs.TCI_CMD_SET_COMMAND_RESP) {
            int command = Packet.byteArrayToInt_Little(data, 0);
            int result = Packet.byteArrayToInt_Little(data, 4);
            if (command == AVIOCTRLDEFs.TCI_CMD_SET_MAX_AWAKE_TIME_REQ) {
                TGLog.d(TGLog.TAG, "mDeviceSettingsInfo.deviceStatus=========result =" + result);
                if (result == 0) {
                    runOnUiThread(() -> {
                        completeSend();
                        mDeviceSettingsInfo.max_awake_time = mSelectWakeMaxTime;
                        sendUpdateSettingBroadcast(mDeviceSettingsInfo);
                    });
                }else{
                    TGThreadPool.executeOnUiThread(() -> {
                        TGToast.showToast(R.string.setting_fail);
                        restoreWakeMaxTime(mLastSelectWakeMaxTime);
                    });
                }
            }
        }
    }

    private void setFlag(ArrayList<SettingData> datas, int position) {
        for (int i = 0; i < datas.size(); i++) {
            if (i == position) {
                datas.get(i).setFlag(1);
            } else {
                datas.get(i).setFlag(0);
            }
        }
    }

    public void setVideoMode(int type) {
        if (!TGDevice.getInstance().isNetwork(mCamera)){
            TGToast.showToast(R.string.txt_network_anomaly);
        }else{
            findViewById(R.id.rl_video_times).setVisibility(AVIOCTRLDEFs.AVIOTC_RECORDTYPE_FULLTIME == type? View.GONE : View.VISIBLE);
            mLastSelectRecordType = mSelectRecordType;
            restoreRecordMode(type);
            mCamera.sendIOCtrl(AVIOCTRLDEFs.IOTYPE_USER_IPCAM_SETRECORD_REQ, AVIOCTRLDEFs.SMsgAVIoctrlSetVideoModeReq.parseContent(0, mSelectRecordType, mSelectRecordStream));
        }
    }

    public void setVideoStream(byte videoStream) {
        if (!TGDevice.getInstance().isNetwork(mCamera)){
            TGToast.showToast(R.string.txt_network_anomaly);
        }else{
            mLastSelectRecordStream = mSelectRecordStream;
            restoreRecordStream(videoStream);
            mCamera.sendIOCtrl(AVIOCTRLDEFs.IOTYPE_USER_IPCAM_SETRECORD_REQ, AVIOCTRLDEFs.SMsgAVIoctrlSetVideoModeReq.parseContent(0, mSelectRecordType, mSelectRecordStream));
        }
    }


    public void setMaxAwakeTime(int maxTime) {
        if (!TGDevice.getInstance().isNetwork(mCamera)){
            TGToast.showToast(R.string.txt_network_anomaly);
        }else{
            mLastSelectWakeMaxTime = mSelectWakeMaxTime;
            restoreWakeMaxTime(maxTime);
            mCamera.sendIOCtrl(AVIOCTRLDEFs.TCI_CMD_SET_MAX_AWAKE_TIME_REQ, AVIOCTRLDEFs.SMsgAVIoctrlGetMaxAwakeTimeReq.parseContent(mSelectWakeMaxTime));
        }
    }


    @Override
    protected void onSetupFailed() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);//remove title bar  即隐藏标题栏
        setContentView(R.layout.activity_solar_video_settings);
        hideActionBar();
        mDeviceSettingsInfo = getIntent().getParcelableExtra(DeviceSettingsActivity.EXT_DEVICE_INFO);
        mCamera = mDeviceSettingsInfo == null? null : CameraHub.getInstance().getCamera(mDeviceSettingsInfo.uuid);
        deviceFeature = DeviceFeatureObjectBox.queryDeviceFeature(mDeviceSettingsInfo.uuid);
        if (mCamera != null) {
            mCamera.registerICameraListener(this);
            if (mCamera.isNotConnected() && checkSDCard()) {
                mCamera.connect();
            }
        }
        initView();
        initData();
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (mCamera != null) {
            mCamera.registerICameraListener(this);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mCamera != null) {
            mCamera.unregisterICameraListener(this);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    private boolean checkSDCard() {
        return mDeviceSettingsInfo != null;//&& mDeviceSettingsInfo.online && mDeviceSettingsInfo.total > 0;
    }


    private void setModeText(int recordType){
        if (recordType == RecordModeConstants.RECORD_MODE_AUTO) {
            settingItemTextView.setContent(R.string.settings_night_vision_auto);
        } else if (recordType == RecordModeConstants.RECORD_MODE_ALARM) {
            settingItemTextView.setContent(R.string.text_mode_2);
        } else if (recordType == RecordModeConstants.RECORD_MODE_FULLTIME) {
            settingItemTextView.setContent(R.string.text_mode_1);
        }
        findViewById(R.id.rl_video_times).setVisibility(recordType == RecordModeConstants.RECORD_MODE_FULLTIME ? View.GONE : View.VISIBLE);
    }

    private void initLimpidData(){
        List<String> list = DeviceFeatureHelper.getResolution(deviceFeature);
        mSelectRecordStream = mDeviceSettingsInfo.recordStream;
        mLastSelectRecordStream = mSelectRecordStream;
        for (int i = 0; i < list.size(); i++){
            String str = list.get(i);
            SettingData settingData = new SettingData(str, i == mDeviceSettingsInfo.recordStream? 1 : 0);
            mLimpidList.add(settingData);
        }
        mLimpidAdapter.notifyDataSetChanged();
    }

    private void initData() {
        if (checkSDCard()) {
            setModeText(mDeviceSettingsInfo.recordType);
            initTimeData();
            initLimpidData();
        }

    }

    private void initTimeData() {
        SettingData mode4 = new SettingData(getString(R.string.text_times_1),null, 0);
        SettingData mode5 = new SettingData(getString(R.string.text_times_2), null, 0);
        SettingData mode6 = new SettingData(getString(R.string.text_times_3), null, 0);
        mTimesList.add(mode4);
        mTimesList.add(mode5);
        mTimesList.add(mode6);

        mSelectWakeMaxTime = mDeviceSettingsInfo.max_awake_time;
        mLastSelectWakeMaxTime = mSelectWakeMaxTime;
        if (mDeviceSettingsInfo.max_awake_time == 20) {
            mode4.setFlag(1);
        } else if (mDeviceSettingsInfo.max_awake_time == 40) {
            mode5.setFlag(1);
        } else if (mDeviceSettingsInfo.max_awake_time == 60) {
            mode6.setFlag(1);
        }
        mTimesAdapter.notifyDataSetChanged();
    }

    private BottomSheetListDialog getBottomSheetDialogHelper() {
        if (bottomSheetListDialog == null) {
            bottomSheetListDialog = new BottomSheetListDialog(this, TGBottomSheetDialog.FROM_SOLAR_VIDEO_MODE);
            bottomSheetListDialog.setCanceledOnTouchOutside(true);
            bottomSheetListDialog.setCancelable(true);
        }
        return bottomSheetListDialog;
    }


    protected void showSettingsBottomSheet() {
        List<BottomSheetListDialog.BottomSheetItem> bottomSheetItems = new ArrayList<>();
        bottomSheetItems.add(new BottomSheetListDialog.BottomSheetItem(BottomSheetListDialog.ACTION_MODE_20, 0, getResources().getString(R.string.settings_night_vision_auto), getResources().getString(R.string.txt_video_mode_auto_tip), mDeviceSettingsInfo.recordType == RecordModeConstants.RECORD_MODE_AUTO));
    //    bottomSheetItems.add(new BottomSheetListDialog.BottomSheetItem(BottomSheetListDialog.ACTION_MODE_40, 0, getResources().getString(R.string.text_mode_1), null, mDeviceSettingsInfo.recordType == RecordModeConstants.RECORD_MODE_FULLTIME));
        bottomSheetItems.add(new BottomSheetListDialog.BottomSheetItem(BottomSheetListDialog.ACTION_MODE_60, 0, getResources().getString(R.string.text_mode_2), getResources().getString(R.string.event_record_tip), mDeviceSettingsInfo.recordType == RecordModeConstants.RECORD_MODE_ALARM));

        CameraBottomSheetDialogHelper.showSettingsBottomSheet(getBottomSheetDialogHelper(), bottomSheetItems, (action, text, position) -> {
            switch (action) {
                case BottomSheetListDialog.ACTION_MODE_20:
                    setVideoMode(AVIOCTRLDEFs.AVIOTC_RECORDTYPE_MANUAL);
                    break;
//                case BottomSheetListDialog.ACTION_MODE_40:
//                    setVideoMode(AVIOCTRLDEFs.AVIOTC_RECORDTYPE_FULLTIME);
//                    break;
                case BottomSheetListDialog.ACTION_MODE_60:
                    setVideoMode(AVIOCTRLDEFs.AVIOTC_RECORDTYPE_ALARM);
                    break;
            }
        });
    }



    private void showTGAlertDialog(String title, String content) {
        new TGAlertDialog(this).builder().setTitle(title).setMessage(content)
                .setPositiveButton(R.string.sure, null).show();

    }

    @Override
    protected void initView() {
        backClickEvent();
        settingItemTextView = findViewById(R.id.settings_video_mode);
        findViewById(R.id.rl_settings_video_mode).setOnClickListener(view -> showSettingsBottomSheet());
        findViewById(R.id.tv_video_times).setOnClickListener(v -> showTGAlertDialog(getString(R.string.event_record_time), getString(R.string.text_dlaglog_content2)));
        findViewById(R.id.tv_video_limpid).setOnClickListener(v -> showTGAlertDialog(getString(R.string.text_video_limpid), getString(R.string.text_dlaglog_content1)));

        setTimeInfo();
        setLimpidInfo();

        if (mDeviceSettingsInfo.isCar) {
            findViewById(R.id.rl_video_limpid).setVisibility(View.GONE);
        } else {
            Box<DeviceFeature> featureBox = DeviceFeatureObjectBox.getDeviceFeature();
            if (mCamera != null) {
                assert featureBox != null;
                DeviceFeature deviceFeature = featureBox.query().equal(DeviceFeature_.uuid, mCamera.uid).build().findFirst();
                if ((deviceFeature != null && !deviceFeature.recordConf)) {
                    findViewById(R.id.rl_video_limpid).setVisibility(View.GONE);
                }
            }
        }

        if (!checkSDCard()) {
            findViewById(R.id.nosdcardlayout).setVisibility(View.VISIBLE);
            findViewById(R.id.rl_video_limpid).setVisibility(View.GONE);
        }
    }

    private void setLimpidInfo() {
        mLimpidAdapter = new SettingAdapter(mLimpidList, this);
        mLimpidAdapter.setCustomText(true);
        mLimpidAdapter.setItemTextSize(14.0f);
        mLimpidAdapter.setMarkTextSize(10.0f);
        ListView listView = findViewById(R.id.settings_list_limpid);
        listView.setAdapter(mLimpidAdapter);
        listView.setOnItemClickListener((parent, view, position, id) -> {
            startSendui();
            setVideoStream((byte) position);
        });
    }

    private void setTimeInfo() {
        mTimesAdapter = new SettingAdapter(mTimesList, this);
        mTimesAdapter.setCustomText(true);
        mTimesAdapter.setItemTextSize(14.0f);
        mTimesAdapter.setMarkTextSize(10.0f);
        ListView listView = findViewById(R.id.settings_list_times);
        listView.setAdapter(mTimesAdapter);
        listView.setOnItemClickListener((parent, view, position, id) -> {
            startSendui();
            switch (position) {
                case 2:
                    setMaxAwakeTime(60);
                    break;
                case 1:
                    setMaxAwakeTime(40);
                    break;
                case 0:
                    setMaxAwakeTime(20);
                    break;
            }
        });
    }
}